package dao

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"listenboos-common/db"
	"listenboos-common/db/gorms"
	"listenboos-common/tools"
	"time"
	"ucenter/model"
)

type UserInfoDao struct {
	conn *gorms.GormConn
}

func NewUserInfoDao(db *db.ListenDB) *UserInfoDao {
	return &UserInfoDao{
		conn: gorms.New(db.Conn),
	}
}
func (u *UserInfoDao) FindByOpenId(ctx context.Context, openId string) (user *model.UserInfo, err error) {
	session := u.conn.Session(ctx)
	err = session.Model(&model.UserInfo{}).Where("wx_open_id = ?", openId).Limit(1).Find(&user).Error
	if err == nil {
		return user, nil
	}
	return user, nil

}
func (u *UserInfoDao) FindById(ctx context.Context, id int64) (user *model.UserInfo, err error) {
	session := u.conn.Session(ctx)
	err = session.Model(&model.UserInfo{}).Where("id = ?", id).Limit(1).Find(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return user, nil

}
func (u *UserInfoDao) Save(ctx context.Context, user *model.UserInfo) error {
	session := u.conn.Session(ctx)
	err := session.Save(user).Error
	if err != nil {
		logx.Error(err)
		return errors.New("create user error")
	}
	return nil
}
func (u *UserInfoDao) UpdateUser(ctx context.Context, id int64, avatarUrl string, nickname string) error {
	session := u.conn.Session(ctx)
	now := tools.ToTimeString(time.Now().UnixMilli())
	err := session.Model(&model.UserInfo{}).Where("id =?", id).Updates(map[string]interface{}{
		"avatar_url":  avatarUrl,
		"nickname":    nickname,
		"update_time": now,
	}).Error
	if err != nil {
		logx.Error(err)
		return errors.New("update user error")
	}
	return nil
}
